import configparser

from kazoo.client import KazooClient
import kazoo.security as se
import json
from tqdm import tqdm


class zkTool:
    def __init__(self, configPath):
        cf = configparser.ConfigParser()
        cf.read(configPath)
        self.initConfig(cf)
        self.create_zk_Client()

    def __init__(self):
        cf = configparser.ConfigParser()
        cf.read("conf", encoding="utf8")
        self.initConfig(cf)
        self.create_zk_Client()
        # print(cf["node"])
        print('connection success !')

    def initConfig(self, cf):
        mps = []
        self.url = cf.get('zk', 'url')
        node = []
        for k in cf["node"]:
            node.append(k)
        node_key = "node"
        node_data = "node_data"
        node_acl = "node_acls"
        for k in node:
            mp = {}
            mp[node_key] = cf.get(node_key, k)
            mp[node_data] = cf.get(node_data, k)
            mp[node_acl] = cf.get(node_acl, k)
            mps.append(mp)
        self.mps = mps

    def create_zk_Client(self):
        self.zk = KazooClient(self.url)
        self.zk.start()

    def createpath(self):
        node_key = "node"
        node_data = "node_data"
        node_acl = "node_acls"
        cli = self.zk
        mapszie = len(self.mps)
        t = tqdm(total=mapszie)
        i = 0
        for k in self.mps:
            path = k.get(node_key)
            data = k.get(node_data).encode(encoding="utf-8")
            acl_ = json.loads(k.get(node_acl))
            acl = [se.ACL(acl_["perms"], se.Id(acl_["scheme"], acl_["id"]))]

            if cli.exists(path):
                cli.set_acls(path, acl)
                cli.set(path, data)
            else:
                cli.create(path, data, acl, makepath=True)
            i += 1
            if (i % 100 == 0):
                t.update(100)
        t.close()


if __name__ == '__main__':
    v = zkTool()
    v.createpath()
